<template>
	<view class="page">
		<u--form labelPosition="left" labelWidth="200rpx" :model="form" :rules="formRules" ref="form">
			<u-gap height="32rpx" bgColor="transparent"></u-gap>
			<view class="form-card-title">患者信息</view>
			<view class="card-container">
				<u-form-item label="姓名" prop="memberName" borderBottom required>
					<u--input v-model="form.memberName" border="none" placeholder="请填写姓名"></u--input>
					<u-icon slot="right" name="account-fill" size="20px" @click="onSelectDiseasePopup"></u-icon>
				</u-form-item>
				<u-form-item label="身份证号" prop="idcard" borderBottom @click="show=true;">
					<u--input v-model="form.idcard" border="none" placeholder="请填写身份证号" @change='calAge'></u--input>
				</u-form-item>
				<u-form-item label="出生日期" prop="birth" borderBottom>
					<uni-datetime-picker type="date" :clear-icon="false" :border='false' v-model="form.birth"
						@change='birthConfirm' />
					<u-icon slot="right" name="arrow-right"></u-icon>
				</u-form-item>
				<u-form-item label="性别" prop="gender" borderBottom>
					<u-radio-group v-model="form.gender" placement="row">
						<u-radio :customStyle="{marginRight: '16px'}" label="男" :name="1"></u-radio>
						<u-radio :customStyle="{marginRight: '8px'}" label="女" :name="2"></u-radio>
					</u-radio-group>
				</u-form-item>
				<u-form-item label="年龄" prop="memberAge" borderBottom required>
					<u--input v-model="form.memberAge" border="none" placeholder="请填写年龄"></u--input>
				</u-form-item>

				<u-form-item label="会诊类型" prop="conMold" borderBottom @click="conMoldShow = true" required>
					<view class="input-text" :class="{'placeholder-color': !conMold}">{{conMold?conMold:'请选择会诊类型'}}
					</view>
					<u-icon slot="right" name="arrow-right"></u-icon>
				</u-form-item>
				<u-form-item label="平急诊" prop="conType" borderBottom required>
					<u-radio-group v-model="form.conType" placement="row">
						<u-radio :customStyle="{marginRight: '16px'}" label="平诊" name="3"></u-radio>
						<u-radio :customStyle="{marginRight: '8px'}" label="急诊" name="6"></u-radio>
					</u-radio-group>
				</u-form-item>
				<u-form-item label="选择医院" prop="expectHospitalId" borderBottom
					@click="onSelectHospitalPopup('hospital')" required>
					<view class="input-text" :class="{'placeholder-color': !expectHospitalId}">
						{{expectHospitalId?expectHospitalId:'请选择期望医院'}}
					</view>
					<u-icon slot="right" name="arrow-right"></u-icon>
				</u-form-item>
				<u-form-item v-if="expectHospitalId" label="科室" prop="deptId" @click="onSelectHospitalPopup('dept')"
					required>
					<view class="input-text" :class="{'placeholder-color': !deptId}">{{deptId?deptId:'请选择科室'}}</view>
					<u-icon slot="right" name="arrow-right"></u-icon>
				</u-form-item>
			</view>
			<u-gap height="32rpx" bgColor="transparent"></u-gap>
			<view class="form-card-title">会诊目的</view>
			<view class="card-container">
				<u-form-item label="" prop="conGoal">
					<u--textarea v-model="form.conGoal" border="none" placeholder="请输入内容"></u--textarea>
				</u-form-item>
			</view>
			<u-gap height="32rpx" bgColor="transparent"></u-gap>
			<view class="form-card-title">患者主诉</view>
			<view class="card-container">
				<u-form-item label="" prop="mainsuit">
					<u--textarea v-model="form.mainsuit" border="none" placeholder="请输入内容"></u--textarea>
				</u-form-item>
			</view>
			<u-gap height="32rpx" bgColor="transparent"></u-gap>
			<view class="form-card-title">初步诊断</view>
			<view class="card-container">
				<u-form-item label="" prop="assessmentcontent">
					<u--textarea v-model="form.assessmentcontent" border="none" placeholder="请输入内容"></u--textarea>
				</u-form-item>
			</view>
			<u-gap height="32rpx" bgColor="transparent"></u-gap>
			<view class="form-card-title">病情照片</view>
			<view class="card-container">
				<u-form-item label="病情照片" prop="imgData" borderBottom>
					<u-upload :fileList="fileList1" @afterRead="afterRead" @delete="deletePic" name="1" multiple
						:maxCount="10"></u-upload>
				</u-form-item>
			</view>
		</u--form>
		<view style="width: 60%;
    margin: 16px auto;
    font-size: 13px;
    color: #5a5a5a;">
			预约时间：{{currentTime}}
		</view>
		<view class="button-group-list">
			<u-button @click="onSubmit" type="primary" text="保存" shape="circle"></u-button>
		</view>

		<!--期望医院选择-->
		<u-picker :show="expectHospitalIdShow" :columns="hospitalSuperiorsList" :closeOnClickOverlay='true'
			keyName="name" @confirm='expectHospitalIdConfirm' @cancel='expectHospitalIdShow=false'
			@close="expectHospitalIdShow = false"></u-picker>

		<!--科室选择-->
		<u-picker :show="deptIdShow" :columns="deptIdList" :closeOnClickOverlay='true' keyName="name"
			@confirm='deptIdConfirm' @cancel='deptIdShow=false' @close="deptIdShow = false"></u-picker>

		<!--会诊类型选择-->
		<u-picker :show="conMoldShow" :columns="conMoldList" :closeOnClickOverlay='true' keyName="name"
			@confirm='conMoldConfirm' @cancel='conMoldShow=false' @close="conMoldShow = false"></u-picker>

		<!--选择患者组件-->
		<select-disease-popup-com ref="selectDiseasePopup" @select="onSelectDisease"></select-disease-popup-com>
		<!--选择医院组件-->
		<select-hospital-popup-com ref="selectHospitalPopup" @select="onSelectHospital"></select-hospital-popup-com>
		<!--出生日期选择-->
		<u-datetime-picker :show="birthShow" v-model="form.birth" mode="date" @confirm='birthConfirm'
			@cancel='birthShow=false' :closeOnClickOverlay='true' :minDate="0" :maxDate='maxDate'></u-datetime-picker>
		<!-- 身份证键盘 -->
		<u-keyboard ref="uKeyboard" mode="card" :show="show" :overlay='false' @close='show=false' :closeOnClickOverlay='true' @change="valChange" @backspace="backspace"></u-keyboard>
	</view>
</template>

<script>
	import config from '@/common/config'
	import {
		addConsultationApi,
		v1HospitalSuperiors,
		v1DepartmentsList
	} from '@/common/api/consultation/add/add.js'
	import {
		validateIdCard,
		getInfoFromIdCard,
		calculateAge
	} from '@/util/utils.js'
	import selectDiseasePopupCom from '@/components/select-disease-popup-com/select-disease-popup-com.vue'
	import selectHospitalPopupCom from '@/components/select-hospital-popup-com/select-hospital-popup-com.vue'
	export default {
		components: {
			selectDiseasePopupCom
		},
		data() {
			return {
				show: false,
				maxDate: Number(new Date()),
				birthShow: false,
				currentTime: '',
				fileList1: [],
				formRules: {
					memberName: [{
						required: true,
						message: '请输入患者姓名',
						trigger: ['blur', 'change']
					}],
					gender: [{
						type: 'number',
						required: true,
						message: '请选择患者性别',
						trigger: ['blur', 'change']
					}],
					idcard: [{
						validator: (rule, value, callback) => {
							if (value && !validateIdCard(value)) {
								return false;
							}
							return true;
						},
						message: '请输入正确的身份证号码',
						trigger: ['blur', 'change']
					}],
					memberAge: [{
						required: true,
						type: 'number',
						message: '请输入患者年龄',
						trigger: ['blur', 'change']
					}],
					conMold: [{
						type: 'number',
						required: true,
						message: '请选择会诊类型',
						trigger: ['blur', 'change']
					}],
					conType: [{
						required: true,
						message: '请选择平急诊类型',
						trigger: ['blur', 'change']
					}],
					expectHospitalId: [{
						required: true,
						message: '请选择医院',
						trigger: ['blur', 'change']
					}],
					deptId: [{
						required: true,
						message: '请选择科室',
						trigger: ['blur', 'change']
					}],
					mainsuit: [{
						required: true,
						message: '请输入患者主诉',
						trigger: ['blur', 'change']
					}],
					assessmentcontent: [{
						required: true,
						message: '请输入初步诊断',
						trigger: ['blur', 'change']
					}]
				},
				conMold: '',
				conMoldShow: false,
				expectHospitalId: '',
				expectHospitalIdShow: false,
				hospitalSuperiorsList: [],
				deptIdList: [],
				deptId: '',
				deptIdShow: false,

				form: {
					memberAge: "",
					memberName: "",
					gender: "1",
					birth: "",
					nation: "",
					cardType: "cert_1",
					idcard: "",
					insuranceType: "",
					insuranceNumber: "",
					phoneNumber: "",
					nativePlace: "",
					height: "",
					weight: "",
					mainsuit: "",
					assessmentcontent: "",
					conGoal: "",
					caseImages: "",
					imgData: "",
					conMold: '',
					conType: "",
					expectHospitalId: "",
					expectHospitalName: "",
					deptName: "",
					deptId: ""

				},
				conMoldList: [
					[{
							value: 1,
							name: "临床会诊"
						},
						{
							value: 2,
							name: "影像诊断"
						},
						{
							value: 3,
							name: "心电诊断"
						},
						{
							value: 4,
							name: "病理诊断"
						},
						{
							value: 5,
							name: "远程示教"
						},
						{
							value: 6,
							name: "精准医疗"
						},
						{
							value: 7,
							name: "卒中急救"
						},
						{
							value: 8,
							name: "病理讨论"
						},
						{
							value: 9,
							name: "护理会诊"
						},
						{
							value: 10,
							name: "远程门诊"
						},
						{
							value: 11,
							name: "检验诊断"
						}
					]
				],

			}
		},
		onShow() {
			// this.getHospitalSuperiors()
			this.getCurrentTime()
		},
		methods: {
			// 按键被点击(点击退格键不会触发此事件)
			valChange(val) {
				// 将每次按键的值拼接到value变量中，注意+=写法
				this.form.idcard += val;
				console.log(this.form.idcard);
			},
			// 退格键被点击
			backspace() {
				// 删除form.idcard的最后一个字符
				if (this.form.idcard.length) this.form.idcard = this.form.idcard.substr(0, this.form.idcard.length - 1);
				console.log(this.form.idcard);
			},
			// 年月日确定按钮
			birthConfirm(e) {
				this.form.memberAge = calculateAge(e);
			},
			// 打开选择医院弹框
			onSelectHospitalPopup(type, id) {
				if (this.form.expectHospitalId) {
					this.$refs.selectHospitalPopup.open(type, this.form.expectHospitalId)
				} else {
					this.$refs.selectHospitalPopup.open(type)
				}
			},
			// 选中医院
			onSelectHospital(e) {
				if (e[0].orgCode) {
					this.form.expectHospitalId = e[0].id
					this.expectHospitalId = e[0].orgName
				} else {
					this.form.deptId = e[0].id
					this.deptId = e[0].deptNickname
				}
			},
			/**
			 * 打开选择患者弹框
			 */
			onSelectDiseasePopup() {
				this.$refs.selectDiseasePopup.open()
			},
			/**
			 * 选择患者
			 */
			onSelectDisease(e) {
				if (e) {
					this.form.memberName = e[0].name
					this.form.idcard = e[0].idNo
					// this.form.gender=Number(e[0].gender)
				}
			},
			// 获取当前时间
			getCurrentTime() {
				const date = new Date();
				const year = date.getFullYear();
				const month = String(date.getMonth() + 1).padStart(2, '0');
				const day = String(date.getDate()).padStart(2, '0');
				const hours = String(date.getHours()).padStart(2, '0');
				const minutes = String(date.getMinutes()).padStart(2, '0');
				const seconds = String(date.getSeconds()).padStart(2, '0');
				this.currentTime = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
			},
			// 通过身份证计算年龄和性别
			calAge(value) {
				console.log('value',value)
				this.$refs.form.validateField('idcard', (res) => {
					if (!res[0]?.message) {
						if (!value) {
							this.form.memberAge = '';
							this.form.gender = null,
								this.form.birth = ''
							return;
						}
						const idCardInfo = getInfoFromIdCard(value);
						if (idCardInfo) {
							this.form.memberAge = idCardInfo.age;
							this.form.gender = idCardInfo.gender
							this.form.birth = idCardInfo.idCardAge
						}
					}
				})

			},
			onSubmit() {
				// 表单验证
				this.$refs.form.validate().then(valid => {
					if (valid) {
						addConsultationApi({
							...this.form
						}).then(res => {
							if (res.code === 1) {
								uni.showToast({
									title: '提交成功',
									icon: 'success'
								});
								uni.redirectTo({
									url: '/pages/consultation/detail/detail?id=' + res.result.id
								});
							}
						})
					}
				});
			},
			// 会诊类型确定按钮
			conMoldConfirm(e) {
				const {
					value,
					name
				} = e.value[0]
				this.form.conMold = value
				this.conMold = name
				this.conMoldShow = false
			},
			// 删除图片
			deletePic(event) {
				this[`fileList${event.name}`].splice(event.index, 1);
			},
			// 新增图片
			async afterRead(event) {
				// 当设置 multiple 为 true 时, file 为数组格式，否则为对象格式
				let lists = [].concat(event.file);
				let fileListLen = this[`fileList${event.name}`].length;
				lists.map((item) => {
					this[`fileList${event.name}`].push({
						...item,
						status: "uploading",
						message: "上传中",
					});
				});
				for (let i = 0; i < lists.length; i++) {
					const result = await this.uploadFilePromise(lists[i].url);
					let item = this[`fileList${event.name}`][fileListLen];
					this[`fileList${event.name}`].splice(
						fileListLen,
						1,
						Object.assign(item, {
							status: "success",
							message: "成功",
							url: result,
						})
					);
					fileListLen++;
				}
			},
			uploadFilePromise(url) {
				return new Promise((resolve, reject) => {
					let a = uni.uploadFile({
						url: "/ygt-api/file/addFile",
						filePath: url,
						name: "file",
						success: (res) => {
							const data = JSON.parse(res.data)
							this.form.caseImages = data.message
							resolve(config.imgURl + data.message);

						},
					});
				});
			},
		}
	}
</script>

<style lang="scss" scoped>
	.page {
		padding: 0 0 calc(64rpx + 120rpx + env(safe-area-inset-bottom)) 0;
		box-sizing: border-box;
	}

	.form-card-title {
		padding: 0 42rpx 16rpx;
		font-size: $ft-size-md;
		color: $text-desc-color;
	}

	.card-container {
		padding: 0 20rpx;
	}

	.button-group-list {
		position: fixed;
		left: 32rpx;
		bottom: calc(32rpx + env(safe-area-inset-bottom));
		display: flex;
		align-items: center;
		justify-content: space-between;
		box-sizing: border-box;
		padding: 0 10rpx;
		width: 686rpx;
		height: 100rpx;
		border-radius: 1000rpx;
		z-index: 10;

		.save-button {
			width: 266rpx;
		}

		.save-entry-button {
			width: 380rpx;
		}
	}
</style>